﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Net;
using Wedo.Utility.Log;
using System.Security.Principal;
using System.Web.Security;

namespace Wedo.Mvc.Utility.Filter
{
    /// <summary>
    /// 错误处理
    /// </summary>
    public class AppHandleErrorFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled == false)
            {
                string controller = filterContext.RouteData.GetRequiredString("controller");
                string action = filterContext.RouteData.GetRequiredString("action").ToLower();

                if (filterContext.Exception is UnauthorizedAccessException)
                {
                    if (filterContext.HttpContext.User.Identity.AuthenticationType == "Windows")
                        return;

                    if (action == "error" || action == "logon")
                        return;

                    if (filterContext.HttpContext.User.Identity.IsAuthenticated == false)
                    {
                        filterContext.Result = new RedirectResult("/Account/LogOn");
                        return;
                    }
                }
                else
                {
                    // 记日志
                    Logger.LogError(controller, action, filterContext.Exception, "出错啦！", "");
                    // 表示异常已处理，直接跳到500显示错误消息

                    filterContext.ExceptionHandled = true;
                    var model = new ViewDataDictionary<HandleErrorInfo>
                        (new HandleErrorInfo(filterContext.Exception, controller, action));

                    ViewResultBase viewResult = null;

                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        viewResult = new PartialViewResult();
                    }
                    else
                    {
                        viewResult = new ViewResult();
                    }

                    viewResult.ViewName = "Error";
                    viewResult.ViewData = model;
                    filterContext.Result = viewResult;
                }
            }
        }
    } 
}